const Router = require('koa-router');
const db = require('../../db');
const moment = require('moment');

const router = new Router({ prefix: '/api/admin' });

// 获取预约列表
router.get('/appointments', async (ctx) => {
  try {
    const { keyword, status, startDate, endDate, teacherId } = ctx.query;
    
    let conditions = [];
    let params = [];
    
    // 添加教师ID筛选条件（通过课程表关联）
    if (teacherId) {
      conditions.push('c.teacher_id = ?');
      params.push(teacherId);
    }
    
    if (keyword) {
      conditions.push('(c.title LIKE ? OR b.contact_name LIKE ?)');
      params.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    if (status) {
      conditions.push('b.status = ?');
      params.push(status);
    }
    
    if (startDate && endDate) {
      conditions.push('DATE(b.booking_date) BETWEEN ? AND ?');
      params.push(startDate, endDate);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    const sql = `
      SELECT 
        b.*,
        c.title as course_title,
        c.teacher_id,
        t.name as teacher_name
      FROM bookings b
      LEFT JOIN courses c ON b.course_id = c.id
      LEFT JOIN teachers t ON c.teacher_id = t.id
      ${whereClause}
      ORDER BY b.created_at DESC
    `;
    
    const result = await db.query(sql, params);
    
    // 格式化日期
    const data = result.map(item => ({
      ...item,
      booking_date: moment(item.booking_date).format('YYYY-MM-DD'),
      created_at: moment(item.created_at).format('YYYY-MM-DD HH:mm:ss')
    }));
    
    ctx.body = {
      code: 0,
      data,
      msg: 'success'
    };
  } catch (error) {
    console.error('获取预约列表失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 批量更新预约状态
router.put('/appointments/batch-status', async (ctx) => {
  let connection;
  try {
    const { ids, status, teacherId } = ctx.request.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      throw new Error('无效的预约ID');
    }
    
    // 验证状态值
    const validStatus = ['upcoming', 'completed', 'cancelled'];
    if (!validStatus.includes(status)) {
      throw new Error('无效的状态值');
    }

    // 开启事务
    connection = await db.beginTransaction();

    // 验证所有预约是否属于该教师的课程
    const checkSql = `
      SELECT COUNT(*) as count
      FROM bookings b
      JOIN courses c ON b.course_id = c.id
      WHERE b.id IN (${ids.join(',')})
      AND c.teacher_id = ?
    `;
    
    const checkResult = await db.query(checkSql, [teacherId], connection);
    if (checkResult[0].count !== ids.length) {
      throw new Error('包含无权操作的预约');
    }

    const sql = `
      UPDATE bookings 
      SET status = ?
      WHERE id IN (${ids.join(',')})
    `;
    
    await db.query(sql, [status], connection);
    
    await db.commit(connection);
    
    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    if (connection) {
      await db.rollback(connection);
    }
    console.error('更新预约状态失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 更新单个预约状态
router.put('/appointments/:id/status', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { status, teacherId } = ctx.request.body;
    
    // 验证状态值
    const validStatus = ['upcoming', 'completed', 'cancelled'];
    if (!validStatus.includes(status)) {
      throw new Error('无效的状态值');
    }

    // 验证预约是否属于该教师的课程
    const checkSql = `
      SELECT COUNT(*) as count
      FROM bookings b
      JOIN courses c ON b.course_id = c.id
      WHERE b.id = ?
      AND c.teacher_id = ?
    `;
    
    const checkResult = await db.query(checkSql, [id, teacherId]);
    if (checkResult[0].count === 0) {
      throw new Error('无权操作此预约');
    }

    const sql = `
      UPDATE bookings 
      SET status = ?
      WHERE id = ?
    `;
    
    await db.query(sql, [status, parseInt(id, 10)]);
    
    ctx.body = {
      code: 0,
      msg: 'success'
    };
  } catch (error) {
    console.error('更新预约状态失败:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

module.exports = router; 